package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Transactional(rollbackFor = Exception.class)
@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Autowired
    TaskinfoMapper taskinfoMapper;
    @Autowired
    TaskinfoLogsMapper taskinfoLogsMapper;
    //redis的封装
    @Autowired
    CacheService cacheService;
    @Override
    public long addTask(Task task) {
        //添加任务到数据库中
        boolean success = addTaskToDb(task);
        if (success){
            //添加任务到redis中
            addTaskToCache(task);
        }
        //返回任务id
        return task.getTaskId();
    }

    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;

        //删除任务，更新日志,把状态改为了已取消
        Task task = updateDb(taskId,ScheduleConstants.EXECUTED);

        //删除redis的数据
        if(task != null){
            removeTaskFromCache(task);
            flag = true;
        }

        return flag;
    }

    @Override
    public Task poll(int type, int priority) {

        String key= type+"_"+priority;
        //从redis中获取任务
        Task task = null;
        try {
            //从redis中获取任务,pop出队取得数据并删除
            String taskJson = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (taskJson!= null) {
                //把返回的数据转成task对象
                task = JSON.parseObject(taskJson, Task.class);
                //更新数据库,把状态改为已经执行
                updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            log.error("Error occurred: ", e);
            throw e;
        }
        return task;
    }

    /**
     * 每5分钟同步一次数据库数据到缓存中
     * PostConstruct注解会在类初始化的时候执行一次
     */
//    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct
    @XxlJob("reloadData")
    public void reloadData() {
        clearCache();
        log.info("数据库数据同步到缓存");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        //查看小于未来5分钟的所有任务加入到缓存中
        List<Taskinfo> allTasks = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime,calendar.getTime()));
        if(allTasks != null && !allTasks.isEmpty()){
            for (Taskinfo taskinfo : allTasks) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
    }

    private void clearCache(){
        // 删除缓存中未来数据集合和当前消费者队列的所有key
        Set<String> futurekeys = cacheService.scan(ScheduleConstants.FUTURE + "*");// future_
        Set<String> topickeys = cacheService.scan(ScheduleConstants.TOPIC + "*");// topic_
        cacheService.delete(futurekeys);
        cacheService.delete(topickeys);
    }

    /**
     * 定时刷新任务一分钟一次
     *
     */

//    @Scheduled(cron = "0 */1 * * * ?")
    @XxlJob("refreshTask")
    public void refreshTask(){
        //分布式锁
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        //如果没有获取到锁就是加锁失败
        if(StringUtils.isNotBlank(token)){
       //获取zset中所有key的值
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        for (String futureKey : futureKeys) {
            String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];

            //只会取出分值小于当前时间的数据
            Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

            if (tasks != null) {
                cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                log.info("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
            }
        }
        }
    }

    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType()+"_"+task.getPriority();
        long success;
        try {
            //删除任务
            if (task.getExecuteTime() <= System.currentTimeMillis()) {
                success = cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
            } else {
                success = cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
            }
            //防止异常
            if (success > 0) {
                log.info("删除redis中的任务成功");
            } else {
                log.error("删除redis中的任务失败");
                throw new RuntimeException("Failed to remove task from Redis");
            }
        } catch (Exception e) {
            log.error("Error occurred: ", e);
            throw e;
        }
    }

    /**
     * 根据id删除taskinfo表中的数据,并修改taskinfoLog表中的状态
     * @param taskId 表示操作的任务的id
     * @param status 表示任务日志中修改的状态,如取消或者已经执行
     * @return 返回操作完之后的task
     */
    private Task updateDb(long taskId,int status) {
        Task task = null;
        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);

            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        }catch (Exception e){
            log.error("task cancel exception taskid={}",taskId);
        }

        return task;

    }

    /**
     * 添加任务到redis中
     * @param task 任务
     */
    private void addTaskToCache(Task task) {
//        设置key的后缀
        String key= task.getTaskType()+"_"+ task.getPriority();

        //获取5分钟后的时间毫秒数,与System.currentTimeMillis比较
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long nextScheduleTime = calendar.getTimeInMillis();

        //1.判断任务是否立即执行,放入list中
        long currentTimeMillis = System.currentTimeMillis();
        //2如果任务的执行时间小于等于当前时间，存入执行任务的队列,之后会不断消费这个队列
        // 比如当前时间为10点,执行时间点在9点,说明选择了立即执行,程序运行到这里已经少于或等于当前时间了
        if (task.getExecuteTime()<=currentTimeMillis){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }else if (task.getExecuteTime()<=nextScheduleTime){
            //如果当前的任务的执行时间大于当前时间，并且小于等于5分钟，放入zset中未来执行
            //只有5分钟后需要执行的任务才放入zset中未来执行,否则放入数据库中
            //数据库会定时5分钟同步到缓存中,查看是否有满足条件的数据
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    private boolean addTaskToDb(Task task) {
        boolean flag = false;
        try {
            //把传过来的任务参数插入数据库中,但是注意时间要转成Date型
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置task的主键,由插入后自动返回
            task.setTaskId(taskinfo.getTaskId());
            //保存任务日志数据,日志就是多了一条version和status,分别表示乐观锁中修改的次数,和当前任务的状态
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (Exception e) {
            log.error("添加任务到数据库中失败", e);
            throw new RuntimeException(e);
        }
        return flag;
    }
}
